const classNames = require('classnames')
const _ = require('../utils')
const { listItemBehavior, listParentBehavior } = require('../behaviors')

_.create('switch', {
  properties: {
    label: String,
    checked: Boolean,
    onText: {
      type: String,
      value: 'ON',
    },
    offText: {
      type: String,
      value: 'OFF',
    },
    helperText: {
      type: String,
      value: null,
    },
    disabled: {
      type: Boolean,
      value: false,
    },
  },

  behaviors: ['wx://form-field', listItemBehavior],

  computed: {
    classes(data) {
      const { classPrefix, checked } = data
      const classes = classNames(classPrefix, {
        [`${classPrefix}-checked`]: checked,
      })

      return classes
    },
  },

  relations: {
    listParent: {
      target: listParentBehavior,
      type: 'parent',
    },
  },

  observers: {
    checked: function (value) {
      this.setData({ value })
    },
  },

  methods: {
    onTap() {
      const checked = !this.data.checked

      this.triggerEvent('change', { checked })
      this.setData({ checked })
    },
  },
})
